import {Component} from '@angular/core';
import {User} from "../entity/user";
import {AuthService} from "../service/auth.service";
import {ToastOptions, ToastData, ToastyService} from "ng2-toasty";
import {Router} from "@angular/router";

@Component({
  moduleId: module.id,
  selector: 'my-register',
  templateUrl: 'register.component.html',
  styleUrls: ['register.component.css'],
})

export class RegisterComponent {

  user = new User();
  repassword: string;
  errorMessage: string;

  constructor(public authService: AuthService, private toastyService: ToastyService, public router: Router) {
  };

  register() {
    if (this.user.passWord !== this.repassword) {
      this.errorMessage = "密码不一致！";
      return false
    }
    if (this.user.phone.toString().length !== 11) {
      this.errorMessage = "手机号码长度应为11位！";
      return false
    }
    const reg: RegExp = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
    if (!reg.test(this.user.email.toString())) {
      this.errorMessage = "电子邮箱格式不正确！";
      return false
    }

    this.authService.register(this.user);
    const toastOptions:ToastOptions = {
      title: "提示信息",
      msg: "注册成功！",
      showClose: true,
      timeout: 1200,
      theme: 'bootstrap',
      onAdd: (toast:ToastData) => {},
      onRemove: (toast:ToastData) => {
        this.router.navigate(['/login']);
      }
    };
    this.toastyService.success(toastOptions);
    this.errorMessage = null;

  }
}
